<?php


namespace App\Services;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Consts\GlobalLoginConst;
use App\Consts\GlobalUserConst;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use Illuminate\Support\Str;

class LoginService extends BaseService
{
    private $_repository;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->LoginRepository;
    }

    public function createLogin($params)
    {
        ArrayHelper::remove($params, ['platform']);

        return $this->_repository->create($params);
    }

    /**
     * 重置令牌
     * @param $login
     * @param $loadData
     * @return int
     */
    public function resetTokenByLogin($login, $loadData)
    {
        return $this->_repository->resetToken($login, $loadData);
    }

    public function getTourist()
    {
        return [
            'id'       => IdBuilder::getUniqueID(time()),
            'identity' => GlobalUserConst::IDENTITY_TOURIST,
            'nickname' => GlobalUserConst::TOURIST_DEFAULT_NICKNAME . Str::random(6),
            'phone'    => '',
            'status'   => GlobalUserConst::STATUS_NORMAL,
            'avatar'   => '',
        ];
    }

    public function getLoginMethodByUserIdFromCache($userId)
    {
        $loginMethod = (int)Cache::getInstance(['user_id' => $userId])->get(CacheKey::USER_LOGIN_METHOD);

        return $loginMethod ?? GlobalLoginConst::LOGIN_METHOD_TEL;
    }

    /**
     * 获取令牌
     * @param $platform
     * @return string
     */
    public function getAccessToken($platform): string
    {
        // 获取token加密secret
        $tokenSecret = GlobalLoginConst::$tokenEncrypt[$platform]['tokenSecret'];

        // 获取当前毫秒级时间戳
        $millisecond = IdBuilder::getMillisecond();
        $time        = ($millisecond / 1000 + GlobalLoginConst::ACCESS_TOKEN_EXPIRED) * 1000;
        $time        = base_convert($time, 10, 36);

        // 获取随机字符串
        $rawStr = Str::random(16);

        // 获取加密向量
        $iv = GlobalLoginConst::$tokenEncrypt[$platform]['tokenIv'];


        return base64_encode(openssl_encrypt($tokenSecret . $time . $rawStr, GlobalLoginConst::TOKEN_ENCRYPT_METHOD, $tokenSecret, 0, $iv));
    }

    /**
     * 获取刷新令牌
     * @param $platform
     * @return string
     */
    public function getRefreshToken($platform)
    {
        // 获取token加密secret
        $tokenSecret = GlobalLoginConst::$tokenEncrypt[$platform]['tokenSecret'];

        // 获取当前毫秒级时间戳
        $millisecond = IdBuilder::getMillisecond();
        $time        = ($millisecond / 1000 + GlobalLoginConst::REFRESH_TOKEN_EXPIRED) * 1000;
        $time        = base_convert($time, 10, 36);

        // 获取随机字符串
        $rawStr = Str::random(16);

        // 获取加密向量
        $iv = GlobalLoginConst::$tokenEncrypt[$platform]['tokenIv'];

        return base64_encode(openssl_encrypt($tokenSecret . $time . $rawStr, GlobalLoginConst::TOKEN_ENCRYPT_METHOD, $tokenSecret, 0, $iv));
    }
}
